package top.andnux.weather.activity;

import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import java.util.ArrayList;
import java.util.List;

import top.andnux.weather.R;
import top.andnux.weather.databinding.ActivityMainBinding;
import top.andnux.weather.fragment.MainFragment;
import top.andnux.weather.fragment.PhotoFragment;


public class MainActivity extends BaseActivity<ActivityMainBinding> {

    private final List<Fragment> fragments = new ArrayList<>();
    private final ViewPager2.OnPageChangeCallback callback = new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            switch (position) {
                case 0:
                    binding.navView.setSelectedItemId(R.id.navigation_home);
                    break;
                case 1:
                    binding.navView.setSelectedItemId(R.id.navigation_photo);
            }
        }
    };

    @Override
    protected ActivityMainBinding createViewBinding(LayoutInflater inflater) {
        return ActivityMainBinding.inflate(inflater);
    }

    @Override
    protected void onCreated(@Nullable Bundle savedInstanceState) {

        fragments.add(new MainFragment());
        fragments.add(new PhotoFragment());

        binding.container.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragments.get(position);
            }

            @Override
            public int getItemCount() {
                return fragments.size();
            }
        });
        binding.container.registerOnPageChangeCallback(callback);
        binding.navView.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.navigation_home) {
                binding.container.setCurrentItem(0);
            } else if (itemId == R.id.navigation_photo) {
                binding.container.setCurrentItem(1);
            }
            return true;
        });
    }

    @Override
    protected void onDestroy() {
        binding.container.unregisterOnPageChangeCallback(callback);
        super.onDestroy();
    }
}